﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GwLib.JqGridMvc;
using GwLib.SampleJqGrid.Models;
using GwLib.SampleJqGrid.Services;

namespace GwLib.SampleJqGrid.Controllers
{
    public class SampleController : Controller
    {
        private readonly PersonService _personSvc = new PersonService();
        //
        // GET: /Sample/

        public ActionResult Index()
        {
            SampleModel model = new SampleModel();
            model.ActionUrls = new JqGridActionUrls { DataSource = Url.Action("PersonGridData") };
            return View(model);
        }
        
        [HttpGet]
        public JsonNetResult PersonGridData(JqGridAjaxEventArgs args)
        {
            IList<Person> persons = _personSvc.GetPersons(args);

            object data = null;
            if (args.TotalRecordCount.HasValue)
            {
                data = SampleModel.Grid.GenerateResults(persons, args);
            }

            return JsonNet(data, JsonRequestBehavior.AllowGet);
        }


        //------------------ I usually put these in a base controller -------------------------
        protected JsonNetResult JsonNet(object data)
        {
            return JsonNet(data, JsonRequestBehavior.DenyGet);
        }

        protected JsonNetResult JsonNet(object data, JsonRequestBehavior behavior)
        {
            return JsonNet(data, null, null, behavior);
        }

        protected JsonNetResult JsonNet(object data, string contentType, System.Text.Encoding contentEncoding)
        {
            return JsonNet(data, contentType, contentEncoding, JsonRequestBehavior.DenyGet);
        }

        protected JsonNetResult JsonNet(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            JsonNetResult result = new JsonNetResult();
            result.Data = data;
            result.ContentType = contentType;
            result.ContentEncoding = contentEncoding;
            result.JsonRequestBehavior = behavior;
            return result;
        }
    }
}
